const express = require('express');
const app = express();
const fs = require('fs');

const { rateLimit } = require('express-rate-limit');
const RedisStore = require('rate-limit-redis');
const RedisClient = require('ioredis');
const requestIp = require('request-ip');

const config = require(__dirname + '/config.js');

app.use(express.static('.'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(requestIp.mw())

const allowlist = config.allowlist;
const client = new RedisClient(config.redis);
const limiter = rateLimit({
    windowMs: 1 * 60 * 1000,
    max: 100,
    standardHeaders: 'draft-7',
    legacyHeaders: false,

    keyGenerator: (req, res) => req.clientIp,
    skip: (req, res) => allowlist.includes(req.clientIp),
    store: new RedisStore({
        client: client,
    }),
});

// Apply the rate limiting middleware to all requests
app.use(limiter);

app.get('/', async function (req, res) {
    res.send('ok');
});

app.post('/test', function (req, res) {
    console.log(req.clientIp, 'coming...');
    res.json({
        status: true,
        msg: 'ok',
        time: parseInt(new Date().getTime() / 1000),
    });
});


app.use(function (err, req, res, next) {
    res.json(err);
});

app.listen(config.port, function () {
    console.log('server is ready');
});
